package com.grandbroad.eim.ui.fragment.vidoe;
import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.easy.west.westclient.api.base.bean.ResultBean;
import com.easy.west.westclient.api.base.bean.VodBean;
import com.easy.west.westclient.api.login.bean.User;
import com.easy.west.westclient.api.vodcommen.bean.CommenList;
import com.easy.west.westclient.api.vodcommen.event.GetVodCommenListEvent;
import com.easy.west.westclient.api.vodcommen.event.SendVodCommenEvent;
import com.grandbroad.eim.adapter.VideoCommenAdapter;
import com.grandbroad.eim.app.MyApplication;
import com.grandbroad.eim.base.BaseRecyclerview;
import com.grandbroad.eim.entry.WhcatBean;
import com.grandbroad.eim.utils.CacheUtils;
import com.grandbroad.eim.utils.ToastUtils;
import com.orhanobut.hawk.Hawk;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/***
 * 评论列表
 */
public class CommentFragment extends BaseRecyclerview {
    private VideoCommenAdapter commenAdapter;
    private VodBean vodBean;
    @Override
    protected void initRecyclerview(RecyclerView recyclerView)
    {
        recyclerView.setAdapter(commenAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        baseRecyclerview.setRefreshing(true);
        baseRecyclerview.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getDataFromNet();
            }
        });
    }



    /**
     * 操作聊天ui
     * @param linearLayout
     * @param editText
     * @param avator
     */
    @Override
    protected void configChatorComment(LinearLayout linearLayout, EditText editText, ImageView avator) {
        //设置显示
        linearLayout.setVisibility(View.VISIBLE);
        User user = CacheUtils.getUser();
        WhcatBean   whcatBean = Hawk.get("wechat");
        if (whcatBean!=null&&TextUtils.isEmpty(user.getAvatar()))
        {
            //如果用户直接通过微信登陆直接采用微信的数据，头像和名字
            x.image().bind(avator,whcatBean.getHeadimgurl());

        }
        else
        {
            //加载头像
            x.image().bind(avator,user.getAvatar());

        }
        //设置软键盘完成点击事件
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //判断是否是“完成”键
                if(actionId == EditorInfo.IME_ACTION_SEND){
                    //执行逻辑
                    String content = editText.getText().toString();
                    if (!TextUtils.isEmpty(content))
                    {
                        //转码
                        //表情和特殊符号可能会引发乱码所以这里进行转码(解码在服务器解决)
                        try {
                            content = URLEncoder.encode(content,"utf-8");
                            editText.setText(null);
                            send(content);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                    else
                    {
                        ToastUtils.show("评论内容不能为空");
                        return true;
                    }
                    //隐藏软键盘
                    InputMethodManager imm = (InputMethodManager) v
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(
                                v.getApplicationWindowToken(), 0);
                    }
                    return true;
                }
                return false;
            }
        });
    }
    /**
     * 发送消息
     * @param content
     */
    private void send(String content) {
        User user = CacheUtils.getUser();
        String access_token = user.getAccess_token();
        long vod_id = vodBean.getId();
        long user_id = user.getId();
        //先模拟不回复模式
        MyApplication.getMoleclient().sendVodCommens(vod_id,user_id,access_token,0,0,content);
    }
    /**
     * 开启事件机制
     * @return
     */
    @Override
    protected boolean setEventOpen()
    {
        return true;
    }

    /**
     * 加载数据
     */
    @Override
    protected void loadData() {
        commenAdapter = new VideoCommenAdapter();
        vodBean = (VodBean) getArguments().getSerializable("bean");
        //getNet
        getDataFromNet();
    }

    /**
     * 从网络上获取数据
     */
    private void getDataFromNet() {
        MyApplication.getMoleclient().getCommens(vodBean.getId(),20);
    }
    /**
     * 获取到评论列表
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getVodCommen(GetVodCommenListEvent eva)
    {
        if (eva.isOk())
        {
            CommenList list = eva.getBean();
            if (list.getStatus()==1)
            {
                baseRecyclerview.setRefreshing(false);
                commenAdapter.setCommenList(list.getData());
                commenAdapter.notifyDataSetChanged();
            }
            else
            {
                baseRecyclerview.setRefreshing(false);
                commenAdapter.setEmpty(true);
                commenAdapter.notifyDataSetChanged();
            }
        }
        else
        {
            baseRecyclerview.setRefreshing(false);
            commenAdapter.setEmpty(true);
            commenAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 发送评论是否成功
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void sendVodCommen(SendVodCommenEvent eva)
    {
        if (eva.isOk())
        {
            ResultBean success = eva.getBean();
            if (success.getStatus()==1)
            {
                ToastUtils.show("评论成功");
                //直接重新加载
                baseRecyclerview.setRefreshing(true);
                loadData();
            }
            else {
                ToastUtils.show("评论失败");
            }
        }
    }
}